package com.mapapp.flutter_mapapp;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.mapapp.flutter_mapapp.activity.BaseActivity;
import com.mapapp.flutter_mapapp.activity.ImmersiveBaseActivity;
import com.mapapp.flutter_mapapp.activity.MineActivity;
import com.mapapp.flutter_mapapp.activity.SearchActivity;
import com.mapapp.flutter_mapapp.activity.StepListActivity;
import com.mapapp.flutter_mapapp.adapter.MapStepAdapter;
import com.mapapp.flutter_mapapp.adapter.MapStepSearchAdapter;
import com.mapapp.flutter_mapapp.application.MyApplication;
import com.mapapp.flutter_mapapp.bean.HomePageShouldBeRefreshed;
import com.mapapp.flutter_mapapp.bean.MapDetailBean;
import com.mapapp.flutter_mapapp.bean.MapResult;
import com.mapapp.flutter_mapapp.bean.ProcessBean;
import com.mapapp.flutter_mapapp.bean.StepFloorBean;
import com.mapapp.flutter_mapapp.bean.StepFloorProcessBean;
import com.mapapp.flutter_mapapp.persenter.MapPersenter;
import com.mapapp.flutter_mapapp.util.MyActivityManager;
import com.mapapp.flutter_mapapp.util.RxBus;
import com.mapapp.flutter_mapapp.view.MapViewInterface;
import com.mapapp.flutter_mapapp.widget.MapNoDateDialog;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.functions.Action1;

public class MainActivity extends ImmersiveBaseActivity implements View.OnClickListener, MapViewInterface,
        BaiduMap.OnMapStatusChangeListener {
    private static final String TAG = "MainActivity";

    @BindView(R.id.bmapView)
    MapView bmapView;
    @BindView(R.id.ll_map_bottom)
    LinearLayout llMapBottom;
    @BindView(R.id.ll_search_bottom)
    LinearLayout llSearchBottom;
    @BindView(R.id.ll_mine_bottom)
    LinearLayout llMineBottom;
    @BindView(R.id.iv_map_bottom)
    ImageView ivMapBottom;
    @BindView(R.id.iv_search_bottom)
    ImageView ivSearchBottom;
    @BindView(R.id.iv_mine_bottom)
    ImageView ivMineBottom;

    private MapPersenter mPersenter;
    private BaiduMap mBaiduMap;
    private MapStatus ms;
    //创建地图首次加载地图，层级判断
    private boolean fistLoadMap = true;
    //地图改动之后，层级判断
    private boolean LoadMap = true;
    //当前地图的层级
    private int CurrentLevel = 1;
    //地图上一层的层级
    private int preLevel = -1;
    //地图下一层的层级
    private int nextLevel = -1;
    //地图信息框
    private InfoWindow mInfoWindow;
    private int currentZoom = 12;
    private boolean isFromSearch = false;//非搜索过来跳楼使用regionId  搜索过来的跳楼使用parentid
    private Observable<HomePageShouldBeRefreshed> observable;
    private boolean serachqu = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mContext = this;
        init();
        mPersenter = new MapPersenter(this, this, lifecycleSubject);
        observable = RxBus.get().register("refresh", HomePageShouldBeRefreshed.class);
        observable.subscribe(new Action1<HomePageShouldBeRefreshed>() {
            @Override
            public void call(HomePageShouldBeRefreshed homePageShouldBeRefreshed) {
                Log.i(TAG,"observable HomePageShouldBeRefreshed");
                if (mPersenter != null) {
                    mPersenter.getFirstMapInfo();
                }
            }
        });
    }

    private void init() {
        setListener();
        initMap();
        ivMapBottom.setImageResource(R.mipmap.icon_barclick_map);
    }

    private void setListener() {
        llSearchBottom.setOnClickListener(this);
        llMineBottom.setOnClickListener(this);
    }

    private void initMap() {
        mBaiduMap = bmapView.getMap();
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Log.i(TAG, "OnMarkerClickListener");
                clickMark(marker);
                return true;
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.ll_search_bottom:
                intent = new Intent(mContext, SearchActivity.class);
                startActivity(intent);
                if(isFromSearch){
                    MyActivityManager.getActivityManager().pop(this);
                }
                break;
            case R.id.ll_mine_bottom:
                intent = new Intent(mContext, MineActivity.class);
                startActivity(intent);
                if (isFromSearch) {
                    MyActivityManager.getActivityManager().pop(this);
                }
                break;
        }
    }

    @Override
    public void addMarks(MapResult mapResult) {
        mBaiduMap.clear();
        isFromSearch = false;
        if(serachqu){
            preLevel = -1;
            nextLevel = -1;
        }else{
            preLevel = mapResult.getPreLevel();
            nextLevel = mapResult.getNextLevel();
        }
        for (int i = 0; i < mapResult.getDetails().size(); i++) {
            MapDetailBean detailBean = mapResult.getDetails().get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_marker_nosetp, null);
            TextView nameTv = view.findViewById(R.id.tv_item_mark_regionname);
            if ("".equals(detailBean.getParentRegionName())) {
                nameTv.setVisibility(View.GONE);
            } else {
                nameTv.setText(detailBean.getParentRegionName());
            }
            TextView addressTv = view.findViewById(R.id.tv_item_mark_address);
            if ("".equals(detailBean.getRegionName())) {
                addressTv.setVisibility(View.GONE);
            } else {
                addressTv.setText(detailBean.getRegionName());
            }
            BitmapDescriptor bd = BitmapDescriptorFactory
                    .fromView(view);
            MarkerOptions ooA = new MarkerOptions()
                    .position(new LatLng(Double.valueOf(detailBean.getLatitude()), Double.valueOf(detailBean.getLongitude())))
                    .icon(bd)
                    .zIndex(9)
                    .draggable(true);
            Marker marker = (Marker) (mBaiduMap.addOverlay(ooA));
            Bundle bundle = new Bundle();
            bundle.putString("regionName", detailBean.getRegionName());
            bundle.putString("regionId", detailBean.getRegionId());
            bundle.putString("bh", detailBean.getBh());
            bundle.putString("levelNumber", detailBean.getLevelNumber() + "");
            bundle.putParcelableArrayList("processes", detailBean.getProcesses());
            marker.setExtraInfo(bundle);
        }
        LoadMap = true;
        ms = new MapStatus.Builder().target(new LatLng(Double.valueOf(mapResult.getDetails().get(0).getLatitude()),
                Double.valueOf(mapResult.getDetails().get(0).getLongitude()))).zoom(mapResult.getDetails().get(0).getLevel() + 11).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
        currentZoom = mapResult.getDetails().get(0).getLevel() + 11;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onDestroy();
        RxBus.get().unregister("refresh", observable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (MyApplication.mSearchResult != null) {
            if(MyApplication.mSearchResult.getType() == 1){
                serachqu = true;
                mPersenter.getdetailsbylevelandbh(MyApplication.mSearchResult.getBh(),MyApplication.mSearchResult.getLevel()+1);
            }else if(MyApplication.mSearchResult.getType() == 0){
                mPersenter.getSearchListInfo(MyApplication.mSearchResult.getParentId());
            }
            MyApplication.mSearchResult = null;
            preLevel = -1;
            nextLevel = -1;
        }
        bmapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        bmapView.onPause();
    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {
    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        int ChangeZoom = (int) Math.floor(mapStatus.zoom);
        Log.i(TAG, "onMapStatusChangeFinish2:" + ChangeZoom);
        if (fistLoadMap) {
            fistLoadMap = false;
            return;
        }
        if (LoadMap) {
            LoadMap = false;
            return;
        }
        Log.i(TAG, "onMapStatusChangeFinish3:" + currentZoom);
        if (ChangeZoom == currentZoom) {
            return;
        }
        if ((ChangeZoom - currentZoom > 0) && nextLevel != -1) {
            CurrentLevel = nextLevel;
            mPersenter.getMapInfoByLevel(CurrentLevel);
        } else if ((currentZoom - ChangeZoom > 0) && preLevel != -1) {
            CurrentLevel = preLevel;
            mPersenter.getMapInfoByLevel(CurrentLevel);
        }
        currentZoom = ChangeZoom;
    }

    /**
     * 搜索界面跳转地图，进行数据处理
     */
    @Override
    public void showSearchResult(StepFloorBean result) {
        mBaiduMap.clear();
        isFromSearch = true;
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_marker_nosetp, null);
        TextView nameTv = view.findViewById(R.id.tv_item_mark_regionname);
        if ("".equals(result.getParentRegionName())) {
            nameTv.setVisibility(View.GONE);
        } else {
            nameTv.setText(result.getParentRegionName());
        }
        TextView addressTv = view.findViewById(R.id.tv_item_mark_address);
        if ("".equals(result.getRegionName())) {
            addressTv.setVisibility(View.GONE);
        } else {
            addressTv.setText(result.getRegionName());
        }
        BitmapDescriptor bd = BitmapDescriptorFactory
                .fromView(view);
        MarkerOptions ooA = new MarkerOptions()
                .position(new LatLng(Double.valueOf(result.getLatitude()), Double.valueOf(result.getLongitude())))
                .icon(bd)
                .zIndex(9)
                .draggable(true);
        Marker marker = (Marker) (mBaiduMap.addOverlay(ooA));
        Bundle bundle = new Bundle();
        bundle.putString("bh", result.getBh());
        bundle.putString("regionName", result.getRegionName());
        bundle.putString("regionId", result.getRegionId());
        bundle.putString("levelNumber", result.getLevelNumber() + "");
        bundle.putParcelableArrayList("processes", result.getProcesses());
        marker.setExtraInfo(bundle);
        ms = new MapStatus.Builder().target(new LatLng(Double.valueOf(result.getLatitude()),
                Double.valueOf(result.getLongitude()))).zoom(19).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
    }

    @Override
    public void noMapData() {
        MapNoDateDialog dialog = new MapNoDateDialog(mContext);
        dialog.setListener(new MapNoDateDialog.OnItemClickListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(mContext, MineActivity.class);
                mContext.startActivity(intent);
            }
        });
        dialog.show();
    }

    /**
     * 地图mark点击处理
     */
    private void clickMark(Marker marker) {
        //数据处理
        Bundle bundle = marker.getExtraInfo();
        LatLng latlng = marker.getPosition();
        String regionName = bundle.getString("regionName");
        String levelNumber = bundle.getString("levelNumber");
        final String bh = bundle.getString("bh");
        final String regionId = bundle.getString("regionId");
        //信息框页面
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_marker, null);
        mInfoWindow = new InfoWindow(view, latlng, -30);
        TextView text = view.findViewById(R.id.map_info_text);
        ImageView cancel = view.findViewById(R.id.map_info_cancel);
        RecyclerView rvStep = view.findViewById(R.id.map_info_step);
        Button start = view.findViewById(R.id.map_info_start);
        //页面数据处理
        if (isFromSearch) {
            ArrayList<StepFloorProcessBean> processBeans = bundle.getParcelableArrayList("processes");
            if (processBeans.size() > 0) {
                rvStep.setVisibility(View.VISIBLE);
            } else {
                rvStep.setVisibility(View.GONE);
            }
            rvStep.setLayoutManager(new LinearLayoutManager(mContext));
            MapStepSearchAdapter adapter = new MapStepSearchAdapter(processBeans, mContext);
            rvStep.setAdapter(adapter);
            start.setVisibility(View.VISIBLE);
            start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, StepListActivity.class);
                    intent.putExtra("parentId", regionId);
                    startActivity(intent);
                    mBaiduMap.hideInfoWindow(mInfoWindow);
                }
            });
        } else {
            ArrayList<ProcessBean> processBeans = bundle.getParcelableArrayList("processes");
            if (processBeans.size() > 0) {
                rvStep.setVisibility(View.VISIBLE);
            } else {
                rvStep.setVisibility(View.GONE);
            }
            rvStep.setLayoutManager(new LinearLayoutManager(mContext));
            MapStepAdapter adapter = new MapStepAdapter(processBeans, mContext);
            rvStep.setAdapter(adapter);
            if (nextLevel != -1) {
                start.setText("下一级");
                start.setVisibility(View.VISIBLE);
                start.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CurrentLevel = nextLevel;
                        mPersenter.getdetailsbylevelandbh(bh, CurrentLevel);
                    }
                });
            } else {
                start.setText("开始");
                start.setVisibility(View.VISIBLE);
                start.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, StepListActivity.class);
                        intent.putExtra("parentId", regionId);
                        startActivity(intent);
                        mBaiduMap.hideInfoWindow(mInfoWindow);
                    }
                });
            }
        }
        text.setText(regionName + "(" + levelNumber + ")");
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaiduMap.hideInfoWindow(mInfoWindow);
                Log.i(TAG, "OnMarkerClickListener    cancel");
            }
        });
        mBaiduMap.showInfoWindow(mInfoWindow);
    }
}
